package app.netant.galgame.bangumi.game;

import java.util.HashSet;
import java.util.Set;

import org.jsoup.select.Elements;

import cn.lily.com.db.container.reader.DataTable;
import cn.lily.com.enviroment.Enviroment;
import cn.lily.com.lang.number.MathUtil;
import app.netant.NetAntBase;
/**
 * bangumi - 列表页面爬虫
 * @author JiaJ
 * @date 2018年6月14日
 *
 */
public class BangumiAntPage extends NetAntBase {

	public BangumiAntPage(String netSite) {
		super(netSite);
	}
	
	public Set<String> extTags(){
		
		Elements activePart = document.select("#wrapperNeue #main .columns.clearit "
				                            + "#columnSubjectBrowserA .section #browserItemList "
				                            + ".item div.inner h3 a");
		
		Set<String> result = new HashSet<String>();
		
		for(int i=0;i<activePart.size();i++){
			
			try {
				
				String href = "http://bangumi.tv"+activePart.get(i).attr("href");
				
				System.out.println("开始连接网站："+href);
				
				BangumiAntDetail detail = new BangumiAntDetail(href);
				
				Set<String> keys = detail.extTags();
				
				for(String key:keys){
					result.add(key);
				}
				
				System.out.println("网站连接成功！");
				
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}

		}
		
		return result;
		
	}
	
	public void analyse(){
		
		Elements activePart = document.select("#wrapperNeue #main .columns.clearit "
						+ "#columnSubjectBrowserA .section #browserItemList "
						+ ".item div.inner h3 a");

		for (int i = 0; i < activePart.size(); i++) {
			
			Enviroment.getEnv().getLogBean().beginLog();
			
			String href = "http://bangumi.tv" + activePart.get(i).attr("href");

			try {
	
				DataTable dataTable = this.getDBManager().executeQueryTable("select * from ${schema}.LEO_BANGUMI_GAME_INFO where GAME_URL='"+href+"'");
				if(dataTable.next()){
					continue;
				}

				System.out.println("开始连接网站：" + href);

				BangumiAntDetail detail = new BangumiAntDetail(href);

				System.out.println("网站连接成功！");
				
				BangumiGameEntity entity = new BangumiGameEntity();
				entity.setGameURL(href);
				detail.setEntity(entity);
				
				detail.analyse();

			} catch (Exception e) {
				e.printStackTrace();
				
				this.getDBManager().executeUpdate("insert into ${schema}.LEO_BANGUMI_GAME_EXCEP (EXCEP_ID,EXCEP_URL,EXCEP_LEVEL) "
						+ "values ('"+System.currentTimeMillis()+""+MathUtil.random(3)+"','"+href+"','2')");
				
				continue;
			}
			
			Enviroment.getEnv().getLogBean().endLog();

		}
		
	}
	
	public static void main(String[] args) {
		BangumiAntPage page = new BangumiAntPage("http://bangumi.tv/game/browser");
		page.extTags();
	}

}
